//
//  WelcomViewController.m
//  GoBigMarket
//
//  Created by 李真 on 16/8/23.
//  Copyright © 2016年 legend. All rights reserved.
//

#import "WelcomViewController.h"
#import "JXTimeButton.h"
#import "ServiceViewController.h"
#import "HomeViewController.h"
#import "RegisterSerViceViewController.h"
@interface WelcomViewController ()
@property JXTimeButton * timeBtn;
@property (weak, nonatomic) IBOutlet UIButton *logInBtn;
@property (weak, nonatomic) IBOutlet UITextField *phoneText;
@property (weak, nonatomic) IBOutlet UITextField *yanzhengmaText;
@property (nonatomic,strong)ServiceViewController *serviceVC;
@property (nonatomic,strong)RegisterSerViceViewController *serViceRegisterView;
@end

@implementation WelcomViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"登录";
    
    self.phoneText.text = nil;
    self.yanzhengmaText.text = nil;
    
    _logInBtn.layer.masksToBounds = YES;
    _logInBtn.layer.cornerRadius = 5;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:[[UIView alloc]init]];

}

-(void)viewWillAppear:(BOOL)animated{
    
    self.tabBarController.tabBar.hidden = YES;
//    self.maBtn.userInteractionEnabled = NO;
}
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    self.phoneText.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.yanzhengmaText.clearButtonMode = UITextFieldViewModeWhileEditing;
    
#pragma mark - 倒计时按钮
    if (!_timeBtn) {
         _timeBtn = [[JXTimeButton alloc]initWithFrame:CGRectMake(XNWindowWidth - 125, 0, 120, 38) AndBeforeTitle:@"获取验证码" AndWorkingMarkStr:@"剩余时间:" AndTimeSum:60 AndTimeButtonStar:^{
          [self timeBtnAction];
        } AndTimeButtonStop:^{
        
     }];
        _timeBtn.userInteractionEnabled = NO;
    }
    _timeBtn.textColor = [UIColor whiteColor];
    _timeBtn.centerY = self.phoneText.centerY;
    _timeBtn.font = [UIFont systemFontOfSize:17];
    _timeBtn.textAlignment = 1;
    _timeBtn.backgroundColor = GDJColor(138, 184, 52);
    _timeBtn.layer.masksToBounds = YES;
    _timeBtn.layer.cornerRadius = 5;

    [self.view addSubview:_timeBtn];
}
#pragma mark - 手机号验证
- (void)textFieldDidEndEditing:(UITextField *)textField{

    if (self.phoneText == textField && textField.text.length > 10) {
        if ([RegularExpressions validateMobile:textField.text]) {
            _timeBtn.userInteractionEnabled = YES;
        }else{
            //手机号不正确
            [self createAlertControllerWithMessage:@"手机号不正确" withState:1];
        }
    }
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    //获取输入框的内容
//    DLog(@"shouldChangeCharactersInRange");
//    DLog(@"textField.text %@",textField.text);
//    DLog(@"range.length %ld",range.length);
//    DLog(@"range.location %ld",range.location);
//    DLog(@"string %@",string);
//    DLog(@"shouldChangeCharactersInRange");
    // +86
    if (range.location > 10) {
      _timeBtn.userInteractionEnabled = YES;
    }
    return YES;
    
}
#pragma mark - 登录按钮
- (IBAction)welcomeBtn:(id)sender {
    
    if (self.phoneText.text.length > 0 && self.phoneText.text.length > 0) {
        UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        //获取Main.storyboard中的首页
        UITabBarController *tabBar = [mainStory instantiateViewControllerWithIdentifier:@"tabBarId"];
        
        [CQNetWorkTools GETWithURL:PostLogin par:@{@"ShouJiHao":self.phoneText.text,@"YanZhengMa":_yanzhengmaText.text,@"Duuid":GETUUID} success:^(id responseObject) {
            //查看错误码
            NSInteger err = [[responseObject valueForKey:@"Err"]integerValue];
            
            if (err != 0) {
                [SVProgressHUD  showWithStatus:[responseObject objectForKey:@"ErrMsg"]];
                [SVProgressHUD dismissWithDelay:1.0];
            }else{
                [[NSUserDefaults standardUserDefaults]setObject:_phoneText.text forKey:@"phoneNum"];
                [[NSUserDefaults standardUserDefaults]setObject:[responseObject valueForKey:@"Token"] forKey: @"Token"];
                [UIApplication sharedApplication].keyWindow.rootViewController = tabBar;
                
                NSUserDefaults *account = [NSUserDefaults standardUserDefaults];
                [account setObject:@"已登录" forKey:LOGIN_STATUS];
                [account synchronize];
            }
        } filed:^(NSError *error) {
            NSLog(@"%@",error);
        }];

    }else{
        
    }
}
#pragma mark - 获取验证码

- (void)timeBtnAction{
    
    if (![RegularExpressions validateMobile:self.phoneText.text]) {
        
        //手机号不正确
        [self createAlertControllerWithMessage:@"手机号不正确" withState:1];
        
    }else{
        //手机号正确
    [CQNetWorkTools GETWithURL:GetYanzhengma par:@{@"ShouJiHao":self.phoneText.text,@"Duuid":GETUUID} success:^(id responseObject) {
        NSLog(@"验证码信息 :%@",responseObject);
        if ([responseObject objectForKey:@"Err"] != 0) {
            NSLog(@"错误信息 ：%@",responseObject[@"ErrMsg"]);
            [SVProgressHUD  showWithStatus:[responseObject objectForKey:@"ErrMsg"]];
            [SVProgressHUD dismissWithDelay:2.0];
        }
    } filed:^(NSError *error) {
        NSLog(@"发生错误  ：%@",error);
    }];
   }
}
#pragma mark - 协议btn
- (IBAction)xieyiBtn:(id)sender {
//    if (!self.serviceVC) {
//        _serviceVC = [[ServiceViewController alloc]init];
//    }
//    [self.navigationController pushViewController:_serviceVC animated:YES];
    if (!self.serViceRegisterView) {
        _serViceRegisterView  = [[RegisterSerViceViewController alloc]init];
    }
     [self.navigationController pushViewController:_serViceRegisterView animated:YES];
}
#pragma mark - 提示框

- (void)createAlertControllerWithMessage:(NSString *)message withState:(NSInteger )state{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        //0.
        if (state == 0) {
            
        } //1.清空手机号
        else if (state == 1){
//            self.phoneText.text = nil;
            
        } //2.清空验证码
        else if (state == 2){
//            self.yanzhengmaText.text = nil;
        }
    }];
    
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
}
#pragma mark - 触摸事件
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.phoneText resignFirstResponder];
    [self.yanzhengmaText resignFirstResponder];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
  
    [self.phoneText resignFirstResponder];
    [self.yanzhengmaText resignFirstResponder];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.timeBtn endTime];
}
@end
